﻿package Welsy4.Connect.commands {
	
	import Welsy4.Connect.business.CommonInfoDelegate;
	import Welsy4.Connect.events.*;
	import Welsy4.Connect.model.ConnectModel;
	import Welsy4.Connect.vo.HttpServiceHandler;
	import Welsy4.Connect.vo.User;

	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.commands.SequenceCommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.cairngorm.control.CairngormEventDispatcher;

	import flash.net.URLVariables;

	import mx.rpc.IResponder;
	import mx.controls.Alert;

	/**
	 * ...
	 * @author DefaultUser (Tools -> Custom Arguments...)
	 */
	public class CommonInfoCommand extends SequenceCommand implements ICommand, IResponder {
		
		
		
		override public function execute(event : CairngormEvent) : void {

			ConnectModel.getInstance().addQueue("CommonInfoCommand.execute");

			this.nextEvent = ChainEvent(event).nextChainedEvent;
			
			
			
			var delegate : CommonInfoDelegate = new CommonInfoDelegate(this);
			delegate.getCommonInfo();
		}

		/**
		 * STEPS
		 * 	a) Verifica se la risposta del server è ConnectModel.SESSION_OK
		 *  b) Verifica se esiste un utente ConnectModel.getInstance().expectedUser o ConnectModel.getInstance().currentUser
		 * 	c) Verifica se c'è un utente loggato
		 * 	d) Verificare se esiste un utente 
		 * 
		 * 
		 * @param	data dove data.resutl è in XML
		 */
		public function result(data : Object) : void {
			ConnectModel.getInstance().addQueue("CommonInfoCommand.result");

			ConnectModel.getInstance().httpServiceHandler = new HttpServiceHandler();
			ConnectModel.getInstance().httpServiceHandler.setXML(data.result);

			/**
			 * a) Verifica se la risposta del server è ConnectModel.SESSION_OK, altrimenti ResponseEvent.ERROR
			 */
			if (ConnectModel.getInstance().httpServiceHandler.getResultStatus() != ConnectModel.SESSION_OK) {
			    
				CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.ERROR, false, ResponseEvent.COMMON_INFO_COMMAND_FAULT, data.result));
				return;
			} 	
			
			/**
			 * b) Verifica se esiste almeno un utente da loggare o da controllare. 
			 *    Altrimenti la sessione Connect non corrisponde alla sessione flex.
			 */
			if (ConnectModel.getInstance().currentUser == null && ConnectModel.getInstance().expectedUser == null) {
				ConnectModel.getInstance().addQueue("CommonInfoCommand.result: neither currentUser nor expectedUser found ");
					
				CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.ERROR, false, ResponseEvent.COMMON_INFO_COMMAND_FAULT, "No user found"));
				return;
			}
			
			/**
			 * c) Verifica se esiste un utente già loggato per questa sessione (sicuramente dovrà essere il nostro currentUser)
			 *    <common><user>
			 */
			if (ConnectModel.getInstance().httpServiceHandler.xml.common.user.length() > 0) {
			    ConnectModel.getInstance().addQueue("CommonInfoCommand.result: <common><user> found");
				/**
				 * procedi con l'autenticazione del nuovo utente expectedUser, 
				 * se esiste ed è cambiato
				 */
				if (ConnectModel.getInstance().currentUser == null) {
				    ConnectModel.getInstance().addQueue("CommonInfoCommand.result: currentUser NOT found. It will be created");
					// la sessione è stata mantenuta, ma per un qualche motivo il currentUser non c'è
					ConnectModel.getInstance().currentUser = ConnectModel.getInstance().expectedUser;
				}
				
				if (ConnectModel.getInstance().expectedUser != null && ConnectModel.getInstance().currentUser.nickname != ConnectModel.getInstance().expectedUser.nickname) {
			        ConnectModel.getInstance().addQueue("CommonInfoCommand.result: try to CHANGE currentUser WITH  expectedUser");
					
					
					autenticateUser(ConnectModel.getInstance().expectedUser);
					
					ConnectModel.getInstance().currentUser = ConnectModel.getInstance().expectedUser;
					ConnectModel.getInstance().expectedUser = null;
					
		  		} else {
				    // prosegui
					ConnectModel.getInstance().addQueue("CommonInfoCommand.result: session and currentUser OK");
					
					this.executeNextCommand();
				}
			} else { 
				/**
				 * Verifica se c'è un expectedUser o un CurrentUser
				 */
				if (ConnectModel.getInstance().currentUser != null) {
					
					ConnectModel.getInstance().addQueue("CommonInfoCommand.result: try authenticating currentUser");
					
					autenticateUser(ConnectModel.getInstance().currentUser);
					
					ConnectModel.getInstance().expectedUser = null;
					
				} else if(ConnectModel.getInstance().expectedUser != null) {
				    
					ConnectModel.getInstance().addQueue("CommonInfoCommand.result: try authenticating expectedUser");
					
					autenticateUser(ConnectModel.getInstance().expectedUser);
				    
					ConnectModel.getInstance().currentUser = ConnectModel.getInstance().expectedUser;
					ConnectModel.getInstance().expectedUser = null;
					
				} else {
					ConnectModel.getInstance().addQueue("CommonInfoCommand.result: never have errors here!");
					
					CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.ERROR, false, ResponseEvent.COMMON_INFO_COMMAND_FAULT, data.result));
				    
				}
				
			}
			
		}

		public function fault(info : Object) : void {
			ConnectModel.getInstance().addQueue("CommonInfoCommand.fault");
			CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.ERROR, false, ResponseEvent.COMMON_INFO_COMMAND_FAULT, ResponseEvent.GENERIC_COMMAND_FAULT));

		}
		/**
		 * standard auth method
		 * 
		 * @param	user
		 */
		private function autenticateUser(user:User):void {
			var chainEventArray : Array = new Array();
			var chainEvent : ChainEvent;
					
			if (user.isAdministrator) {
				
				ConnectModel.getInstance().addQueue("CommonInfoCommand.autenticateUser: authenticating ADMIN...");
					
				
			    chainEventArray.push(new AuthenticationEvent(AuthenticationEvent.SECURE_LOG_IN, new URLVariables("login=" + user.nickname + "&password=" + user.getPassword())));
						
				chainEventArray.push(new PrincipalListEvent(PrincipalListEvent.SET_CURRENT_USER_ID));
						
				chainEventArray.push(this.nextEvent);
					
			} else {
				
				ConnectModel.getInstance().addQueue("CommonInfoCommand.autenticateUser: authenticating user...");
				
				chainEventArray.push(new AuthenticationEvent(AuthenticationEvent.LOG_IN, new URLVariables("login=" + user.nickname)));
						
				chainEventArray.push(new PrincipalListEvent(PrincipalListEvent.SET_CURRENT_USER_ID));
						
				chainEventArray.push(this.nextEvent);
						
			}
					
			chainEvent = EventChainFactory.chainEvents(chainEventArray);
			CairngormEventDispatcher.getInstance().dispatchEvent(chainEvent);
			
		}
		
		

	}

}